/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ManageJFrame;
import ManageBLL.BLLManufacture;
import ManageBLL.BLLProduct;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.imageio.ImageIO;
/**
 *
 * @author Pham
 */
public class JDialogProduct extends javax.swing.JDialog {
    BLLManufacture bllManu;
    BLLProduct bllPro;
    JFileChooser fcImage;
    File fImage;
    boolean insert = false;
    int ProductUpdateID = -1;
    /**
     * Creates new form JDialogProduct
     */
    public JDialogProduct(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        bllManu = new BLLManufacture();
        bllPro = new BLLProduct();
        insert = true;
        //initialize Components
        initComponents();
        jlbTitle.setText("Thêm sản phẩm");
        
        //add Items to combobox cbManu
        addItemtoCbManufacture();
        
        //add btnsave Action
        jbtnSave.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                jbtnSaveactionPerformed(e);
            }

            
        });
    }
    
    public JDialogProduct(java.awt.Frame parent, boolean modal, int ID)
    {
        super(parent, modal);
        bllManu = new BLLManufacture();
        bllPro = new BLLProduct();
        insert = false;
        this.ProductUpdateID = ID;
        //initialize Components
        initComponents();
        jlbTitle.setText("Sửa sản phẩm");
        
        //add Items to combobox cbManu
        addItemtoCbManufacture();
        
        //populate data
        populatePro(ID);
        
        //add btnsave Action
        jbtnSave.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                jbtnSaveactionPerformed(e);
            }

        });
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    private void initComponents() {//GEN-BEGIN:initComponents

        jPanel1 = new javax.swing.JPanel();
        jTbFunction = new javax.swing.JToolBar();
        jbtnNew = new javax.swing.JButton();
        jbtnSave = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jtxtProName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jcbManu = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jtxtProPrice = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jbtnImage = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jtxtProWarranty = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtxtaProPromotion = new javax.swing.JTextArea();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtxtaProDescription = new javax.swing.JTextArea();
        jlbImage = new javax.swing.JLabel();
        jlbTitle = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTbFunction.setFloatable(false);
        jTbFunction.setRollover(true);

        jbtnNew.setIcon(new ImageIcon(new ImageIcon(getClass().getResource("../Images/new.png"))
            .getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH)));
    jbtnNew.setFocusable(false);
    jbtnNew.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbtnNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbtnNew.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jbtnNewActionPerformed(evt);
        }
    });
    jTbFunction.add(jbtnNew);

    jbtnSave.setIcon(new ImageIcon(new ImageIcon(getClass().getResource("../Images/save.png"))
        .getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH)));
jbtnSave.setFocusable(false);
jbtnSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jbtnSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jTbFunction.add(jbtnSave);

jLabel1.setText("Tên SP");

jLabel2.setText("Hãng sản xuất");

jcbManu.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

jLabel3.setText("Giá");

jLabel4.setText("Hình");

jbtnImage.setText("Chọn hình");
jbtnImage.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbtnImageActionPerformed(evt);
    }
    });

    jLabel5.setText("Bảo hành");

    jLabel6.setText("Khuyến mãi");

    jtxtaProPromotion.setColumns(20);
    jtxtaProPromotion.setRows(5);
    jScrollPane1.setViewportView(jtxtaProPromotion);

    jLabel7.setText("Mô tả sản phẩm");

    jtxtaProDescription.setColumns(20);
    jtxtaProDescription.setRows(5);
    jScrollPane2.setViewportView(jtxtaProDescription);

    jlbImage.setMaximumSize(new java.awt.Dimension(99, 99));
    jlbImage.setMinimumSize(new java.awt.Dimension(88, 88));
    jlbImage.setPreferredSize(new java.awt.Dimension(99, 99));

    jlbTitle.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
    jlbTitle.setForeground(new java.awt.Color(204, 0, 51));
    jlbTitle.setText("Thêm sản phẩm mới");

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jTbFunction, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(24, 24, 24)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel7)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jScrollPane2)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2)
                                .addComponent(jLabel3)
                                .addComponent(jLabel4))
                            .addGap(20, 20, 20)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jtxtProName)
                                .addComponent(jcbManu, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jtxtProPrice)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jbtnImage, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jlbImage, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 76, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel5)
                                    .addGap(23, 23, 23)
                                    .addComponent(jtxtProWarranty, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel6)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGap(0, 0, Short.MAX_VALUE)
                            .addComponent(jlbTitle)
                            .addGap(247, 247, 247)))
                    .addGap(26, 26, 26))))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jTbFunction, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jlbTitle)
            .addGap(24, 24, 24)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(jtxtProWarranty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel6)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jtxtProName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2)
                        .addComponent(jcbManu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jtxtProPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jbtnImage)
                            .addComponent(jLabel4))
                        .addComponent(jlbImage, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel7)
            .addGap(8, 8, 8)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 13, Short.MAX_VALUE))
    );

    pack();
    }//GEN-END:initComponents

    private void jbtnImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnImageActionPerformed
        try{
           fcImage = new JFileChooser();
           fcImage.showOpenDialog(this);
           fImage = fcImage.getSelectedFile();
           //JOptionPane.showMessageDialog(null, fImage.toString());
           if(fImage != null){
                ImageIcon icon = new ImageIcon(fImage.toString());
                Image img = icon.getImage().getScaledInstance(91, 91, Image.SCALE_SMOOTH);
                ImageIcon icon2 = new ImageIcon(img);
                jlbImage.setIcon(icon2);
           }
           
        }
        catch(Exception e){
            System.err.print(e.getMessage());
        }
    }//GEN-LAST:event_jbtnImageActionPerformed

    private void jbtnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNewActionPerformed
        jtxtProName.setText("");
        jtxtProPrice.setText("");
        jtxtProWarranty.setText("");
        jtxtaProDescription.setText("");
        jtxtaProPromotion.setText("");
        jlbImage.setIcon(null);
    }//GEN-LAST:event_jbtnNewActionPerformed

    //method add Items to combobox cbManufacture
    private void addItemtoCbManufacture()
    {
        try{
            DefaultComboBoxModel cbModel = bllManu.getComboboxModelManu();
            jcbManu.setModel(cbModel);
        }
        catch(Exception e){
            System.err.print(e.getMessage());
        }
    }
    
    //method check avaiable input
    private String checkInput()
    {
        String result = "";
        if("".equals(jtxtProName.getText().trim()))
        {
            result += "Bạn phải nhập tên sản phẩm.\n";
        }
        if("".equals(jtxtProPrice.getText().trim()))
            result += "Bạn phải nhập giá.\n";
        return result;
    }
    
    //method write image to directory
    private void writeImage(File file, String savePath )
    {
        
        try
        {
//            JOptionPane.showMessageDialog(null, savePath);
            BufferedImage buffImage;
            buffImage = ImageIO.read(file);
            File checkExist = new File(savePath);
            if(!checkExist.exists())
                ImageIO.write(buffImage, "png", new File(savePath));
//            JOptionPane.showMessageDialog(null, "success");
        }
        catch(IOException | HeadlessException ex){
            System.err.print(ex.getMessage());
        }
            
    }
    
    //populate data with Product ID
    private void populatePro(int ID) {
        BLLProduct Pro = bllPro.getProductByID(ID);
        if(Pro != null)
        {
            jtxtProName.setText(Pro.getProductName());
            jtxtProPrice.setText(String.valueOf(Pro.getProductPrice()));
            jtxtProWarranty.setText(Pro.getProductWarranty());
            jtxtaProDescription.setText(Pro.getProductDescription());
            jtxtaProPromotion.setText(Pro.getProductPromotion());
            jcbManu.setSelectedItem(Pro.getBllManu().getManufactureName());
            ImageIcon iconTamp = new ImageIcon("D:\\wamp\\www\\shopcomputer\\public\\default\\images\\products\\" + Pro.getProductImage());
            Image img = iconTamp.getImage().getScaledInstance(91, 91, Image.SCALE_SMOOTH);
            ImageIcon iconPro = new ImageIcon(img);
            jlbImage.setIcon(iconPro);
        }
        
    }
    
    ////////////method action//////////////////////
    //method action btnSave 
    private void jbtnSaveactionPerformed(ActionEvent e) {
        try{
            
            if("".equals(checkInput()))
            {
                String ProName = jtxtProName.getText().trim();
                long ProPrice = Long.valueOf(jtxtProPrice.getText().trim());
                String ProWarranty = jtxtProWarranty.getText().trim();
                String ProPromotion = jtxtaProPromotion.getText().trim();
                String ProDescription = jtxtaProDescription.getText().trim();
                String ProImageName = "";
                if(fImage != null){
                    ProImageName = fImage.getName();
                    writeImage(fImage, "D:\\wamp\\www\\shopcomputer\\public\\default\\images\\products\\" + ProImageName);
                }
                int ProQuantity = 0;
                
                
                Date ProDate = new Date();
                
                bllPro.setProductName(ProName);
                bllPro.setProductPrice(ProPrice);
                bllPro.setProductQuantity(ProQuantity);
                bllPro.setProductImage(ProImageName);
                bllPro.setProductWarranty(ProWarranty);
                bllPro.setProductDescription(ProDescription);
                bllPro.setProductPromotion(ProPromotion);
                bllPro.setProductDateUpdate(ProDate);
                bllPro.setBllManu(bllManu.getManuIDbyName(jcbManu.getSelectedItem().toString()));
                if(insert)
                {
//                    JOptionPane.showMessageDialog(this, "insert");
                    if(bllPro.exeInsertProduct(bllPro))
                        JOptionPane.showMessageDialog(this, "Đã thêm sản phẩm");
                }
                else{
                    if(ProductUpdateID != -1)
                    {
                        bllPro.setProductID(ProductUpdateID);
                        if(bllPro.exeUpdateProduct(bllPro))
                            JOptionPane.showMessageDialog(this, "Đã cập nhật sản phẩm");
//                          JOptionPane.showMessageDialog(this, "update " + bllPro.getProductID());
                    }
                    
                }
                    
                
            }
            else
                JOptionPane.showMessageDialog(this, checkInput());
            
        }
        catch(NumberFormatException | HeadlessException ex)
        {
            System.err.print(ex.getMessage());
        }
        
    }
    
    
    
    ///////////end method action//////////////////
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JDialogProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JDialogProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JDialogProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JDialogProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                JDialogProduct dialog = new JDialogProduct(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar jTbFunction;
    private javax.swing.JButton jbtnImage;
    private javax.swing.JButton jbtnNew;
    private javax.swing.JButton jbtnSave;
    private javax.swing.JComboBox jcbManu;
    private javax.swing.JLabel jlbImage;
    private javax.swing.JLabel jlbTitle;
    private javax.swing.JTextField jtxtProName;
    private javax.swing.JTextField jtxtProPrice;
    private javax.swing.JTextField jtxtProWarranty;
    private javax.swing.JTextArea jtxtaProDescription;
    private javax.swing.JTextArea jtxtaProPromotion;
    // End of variables declaration//GEN-END:variables

    
}
